package main

import (
	"fmt"
	"strconv"

	"github.com/0xAX/notificator"
	"github.com/getlantern/systray"
	"github.com/robotn/gohook"
	"keyHook/config"
	"keyHook/musicplayer"
)

var done = make(chan bool, 1)
var notify = notificator.New(notificator.Options{
	DefaultIcon: "icon/logo.png",
	AppName:     "AppName",
})

func main() {
	go config.InitConfig()
	go hookReady()
	systray.Run(config.OnReady, nil)
}

// 全局监听键盘事件
func hookReady() {
	hooks := hook.Start()
	fmt.Println("全局键盘监听已开启!")
	var song string
	defer hook.End()
	for ev := range hooks {
		if ev.Kind == hook.KeyUp {
			//	监听键盘弹起
			fmt.Printf("——)%d(— keycode\n", ev.Keycode)
			if config.Isdebug {
				_ = notify.Push("按键KeyCode", strconv.Itoa(int(ev.Keycode)), "/home/user/icon.png", notificator.UR_NORMAL) // Linux有效
			}
			song = "" // 默认为 空字符串
			for key, value := range config.Cfg {
				//fmt.Printf("\t key的类型 %T Key->%s ,Value->%s \n", key, key, value)
				// 打印按键keycode 方便映射其他按键
				// 转换成 int 类型
				atoi, err := strconv.Atoi(key)
				if err != nil {
					// 已有映射关系
					a := config.KeyMap[key]
					if a == ev.Keycode {
						//传入地址
						song = value
					}
				} else {
					// 为 keycode 新映射
					if uint16(atoi) == ev.Keycode {
						//传入地址
						song = value
					}
				}
			}
			if song != "" {
				// 调用 播放mp3
				go musicplayer.PlayerMusic(done, song)
				// 等待任务完成
				<-done
			}
			// 监听键盘弹起 结束位置
		}
	}
}
